package com.tangqiang.childrenname.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author tqiang
 * @date 2019-08-28 17:06
 */
@Service
public class NameSaveService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private String folder = "msg";
    private String fileExt = ".msg";

    private File currentFile;

    public NameSaveService() {
        init();
    }

    public void init() {
        try {
            File fileFolder = new File(folder);
            if (!fileFolder.exists() || !fileFolder.isDirectory()) {
                fileFolder.mkdirs();
            }

            File[] files = fileFolder.listFiles((dir, name) -> name.endsWith(fileExt));
            if (files != null && files.length > 0) {
                Arrays.sort(files, (file1, file2) -> Long.compare(file2.lastModified(), file1.lastModified()));
                currentFile = files[0];
            } else {
                String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                currentFile = new File(fileFolder, date + fileExt);
            }
            logger.info("Init currentFile:" + currentFile.getAbsolutePath());
        } catch (Exception e) {
            logger.error("Init error!", e);
        }
    }

    public Map<String, Object> addName(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String line = JSONObject.toJSONString(params) + "\n";
            logger.info("add :" + line + " to file:" + currentFile.getAbsolutePath());
            FileUtils.writeStringToFile(currentFile, line, StandardCharsets.UTF_8.toString(), true);
            result.put("add", "success");
        } catch (Exception e) {
            logger.error("addName error !", e);
        }
        return result;
    }

    public Map<String, Object> removeName(Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String removeName = (String) params.get("name");
            if (!StringUtils.isEmpty(removeName)) {
                List<String> list = FileUtils.readLines(currentFile, StandardCharsets.UTF_8.toString());
                for (int i = list.size() - 1; i >= 0; i--) {
                    String line = list.get(i);
                    JSONObject jsonObject = JSONObject.parseObject(line);
                    String name = jsonObject.getString("name");
                    if (removeName.equals(name)) {
                        logger.info("remove :" + line);
                        list.remove(i);
                    }
                }
                FileUtils.writeLines(currentFile, list, false);
                result.put("remove", "success");
            }
        } catch (Exception e) {
            logger.error("addName error !", e);
        }
        return result;
    }

    public List<Map<String, Object>> getSelected(Map<String, Object> params) {
        List<Map<String, Object>> result = new ArrayList<>();
        try {
            List<String> list = FileUtils.readLines(currentFile, StandardCharsets.UTF_8.toString());
            for (int i = 0; i < list.size(); i++) {
                String line = list.get(i);
                JSONObject jsonObject = JSONObject.parseObject(line);
                result.add(new HashMap<>(jsonObject));
            }
            result.sort((o1, o2) -> {
                float score1 = Float.parseFloat(o1.getOrDefault("score", 0).toString());
                float score2 = Float.parseFloat(o2.getOrDefault("score", 0).toString());
                return score1 > score2 ? -1 : 1;
            });
        } catch (Exception e) {
            logger.error("getSelected error !", e);
        }
        return result;
    }

    public Map<String, Object> saveScore(List<Map<String, Object>> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            File newFile = new File(currentFile.getParentFile(), date + fileExt);
            currentFile = newFile;
            List<String> list = new ArrayList<>();
            for (Map<String, Object> param : params) {
                list.add(JSONObject.toJSONString(param));
            }
            FileUtils.writeLines(currentFile, list, false);
            result.put("change", "success");
        } catch (Exception e) {
            logger.error("change error !", e);
        }
        return result;
    }
}
